const { resolve } = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ConsoleWebpackPlugin = require('../scripts/plugins/console-webpack-plugin')
const SetScriptTimePlugin = require('../scripts/plugins/set-script-time-plugin')
const EditEmitPlugin = require('../scripts/plugins/edit-emit-pulgin')
const { ProgressPlugin } = require('webpack')


const baseConfig = (mode) => {
  const config = {
    mode,
    entry: resolve(__dirname, '../src/main.js'),
    output: {
      filename: 'js/[name].js',
      path: resolve(__dirname, '../dist')
    },
    module: {
      rules: [
        {
          test: /\.vue$/,
          loader: 'vue-loader'
        },
        {
          test: /\.html$/,
          loader: 'html-loader'
        },
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader',
            'postcss-loader'
          ]
        },
        {
          test: /\.less$/,
          use: [
            'style-loader',
            'css-loader',
            'postcss-loader',
            'less-loader'
          ]
        },
        {
          test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/
        },
        {
          test: /\.ts$/,
          use: [
            {
              loader: 'ts-loader',
              options: {
                appendTsSuffixTo: [/\.vue$/]
              }
            }
          ],
          exclude: /node_modules/
        },
        {
          test: /\.(png|svg|jpe?g|gif)$/i,
          type: 'asset/resource',
        },
        {
          test: /\.(woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
        },
      ]
    },
    plugins: [
      new VueLoaderPlugin(),
      new HtmlWebpackPlugin({
        template: resolve(__dirname, '../public/index.html'),
        minify: {
          // 移除空格
          collapseWhitespace: true,
          // 移除注释
          removeComments: true
        },
        publicPath: '.'
      }),
      // new ConsoleWebpackPlugin()
      new SetScriptTimePlugin(),
      new ProgressPlugin()
    ],
    optimization: {
      minimize: false,
      splitChunks: {
        cacheGroups: {
          vue: {
            test: /[\\/]node_modules[\\/](@?vue)[\\/]/,
            name: 'vue',
            chunks: 'all',
            priority: -9
          },
          vender: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
            priority: -10
          },
          default: {
            name: 'common',
            chunks: 'initial',
            minChunks: 2,  // 模块被引用两次以上才进行抽离
            priority: -20
          },
        }
      }
    },
    resolve: {
      extensions: ['.js', '.vue', '.ts', '.css', '.less', '.json']
    }
  }

  return config
}

module.exports = baseConfig
